package models

import (
	"github.com/google/uuid"
	"gorm.io/gorm"
	"mishop/entitys"
)

type Order struct {
	gorm.Model
	OrderNo            string              `json:"order_no"`
	OriginalTotalPrice float32             `json:"original_total_price"`
	ActualTotalPrice   float32             `json:"actual_total_price"`
	PayStatus          entitys.PayStatus   `json:"pay_status"`
	PayType            entitys.PayType     `json:"pay_type"`
	OrderStatus        entitys.OrderStatus `json:"order_status"`
	OrderItems         []OrderItem         `json:"order_items" binding:"required"`
	db                 *gorm.DB            `json:"-"`
}

func (Order) TableName() string {
	return "orders"
}

func (p *Order) BeforeCreate(tx *gorm.DB) (err error) {
	p.OrderNo = uuid.New().String()
	return nil
}

func (p *Order) Create(c *Order) (*Order, error) {
	result := p.db.Create(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *Order) Update(c *Order) (*Order, error) {
	result := p.db.Updates(c)
	if result.Error != nil {
		return nil, result.Error
	}
	return c, nil
}

func (p *Order) Delete(orderId int) error {
	result := p.db.Delete(&Order{}, orderId)
	return result.Error
}

func (p *Order) FindByID(order_id uint) (model *Order, err error) {
	model = &Order{}
	model.ID = order_id
	result := p.db.First(model)
	err = result.Error
	return
}

func (p Order) FindByUserID(page, rows int, user_id uint) (pages *Pages, error error) {
	var data []Order
	var all int64
	pages = &Pages{}
	query := p.db.Model(Order{}).Where("user_id = ?", user_id)
	//all
	result := query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	query.Limit(rows).Offset((page - 1) * rows).Find(&data)
	result = query.Count(&all)
	if result.Error != nil {
		return nil, result.Error
	}
	return NewPages(page, rows, all, data), nil
}

type IOrder interface {
	FindByID(orderId uint) (*Order, error)
	FindByUserID(page, rows int, userId uint) (pages *Pages, error error)
	Create(c *Order) (*Order, error)
	Update(c *Order) (*Order, error)
	Delete(orderId int) error
}

func NewOrder(db *gorm.DB) IOrder {
	return &Order{db: db}
}
